import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Input, Popconfirm, Modal, Checkbox, Collapse, Icon, Message as msg, Anchor, Divider} from 'antd';
import PropTypes from 'prop-types';
import routes from '../routes';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH, DATE_FORMAT, FORM_ROW_OPTIONS, DATETIME_FORMAT} from '../../constants';
import {PERMISSION, repairTypeSale, repairTypeUnSale, tuClaimAthType, PANEL_CARD_COL_SPAN} from '../constants';
import {injectIntl, language} from '../intl';
import {formatAmount, conventEnumValueToString, formatDateTime, uuid} from '../../utils';
import TextInput from 'Shared/components/TextInput';
import styles from '../style.css';
import PartMultiSelectPanel from './PartMultiSelectPanel';
import LocalizeInputNumber from '../../common/LocalizeInputNumber';
import WrappedDatePicker from '../../common/WrappedDatePicker';
import SearchSelect from 'Shared/components/SearchSelect';
import SearchInput from 'Shared/components/SearchInput';
import WrappedSelect from '../../common/WrappedSelect';
import Return from '../../common/Return';
import ClaimApplySelectPanel from './ClaimApplySelectPanel';
import SubClaimSelectPanel from './SubClaimSelectPanel';
import FaultModeSelectPanel from './FaultModeSelectPanel';
import DutyUnitSelectPanel from './DutyUnitSelectPanel';
import VehicleSoldSelectPanel from './VehicleSoldSelectPanel';
import MaterialTablePanel from './MaterialTablePanel';
import WorkItemTablePanel from './WorkItemTablePanel';
import WorkItemSelectPanel from './WorkItemSelectPanel';
import ClaimHistoryPanel from './ClaimHistoryPanel';
import ClaimAthPanel from './ClaimAthPanel';
import PartAssistPanel from './PartAssistPanel';
import {newOrderValidator, newOrUpdateOrderValidator} from '../validator';
import {currency, repairType, vehicleStatus, claimUsedPartDealCategory, claimAthType,
    customerType, dutyUnitType, faultType, fileType} from '../../Enum';
import {hasPermissions, getUrl} from '../utils';
import {onSelectPartAccessory, onChangeSwitchVehicle, onChangeClaimApplyDetail,
    onChangeSubClaimDetail, onChangeSwitchVehicleIsOtherArea} from './OnChangValidator';
import {getDetail, faultModeQuickly, getDutyUnitsQuickly, getVehicleSoldsQuickly,
    getWorkItems, getcClaimHistoriesList, getMgmtRates, claimApplieDetail,
    getPartServicePrices, subClaimDetail, getPartCategory, getWarrantyPolicy, subDealersQuery, subDealersQuickly} from '../api';
import FaultItemSelectPanel from '../../common/FaultItemSelect/SelectEdit';
import DealerSelectPanel from '../../common/DealerSelect/SelectEdit';
import moment from 'moment';
const {Link} = Anchor;
const {Panel} = Collapse;
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
const repairTypeSaleList = repairTypeSale.toList(language);
const repairTypeUnSaleList = repairTypeUnSale.toList(language);
const claimAthTypeList = claimAthType.toList(language);
const faultTypeList = faultType.toList(language);
const tuClaimAthTypeList = tuClaimAthType.toList(language);
const dateTime = new Date();

class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {
            isOut: false,
            outFee: 0,
            isOtherArea: false
        },
        showClaimApply: false,
        showSubClaim: false,
        showDutyUnit: false,
        showVehicle: false,
        showPartMultiSelectPanel: false,
        showPartAssistPanel: false,
        showWorkItem: false,
        details: [],
        claimWorkItemDetails: [],
        claimApprovedHis: [],
        isAccessory: false,
        claimAthDetails: [],
        claimMaterialDetails: [],
        workItem: {},
        claimHistories: {},
        mgmtRate: 0,
        isFaultItem: false,
        partCategoryId: '',
        faultItemNameData: '',
        isSupplier: false
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok) {
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details,
                            claimWorkItemDetails: res.data.claimWorkItemDetails,
                            claimApprovedHis: res.data.claimApprovedHis,
                            claimAthDetails: res.data.claimAthDetails,
                            claimMaterialDetails: res.data.claimMaterialDetails,
                            isSupplier: !res.data.supplierId
                        });
                        this.getClaimHistories(res.data.vin, res.data.createTime, this.props.id);
                        this.getWorkItems(res.data.productCategoryCode, res.data.brandId);
                    } else
                        this.setState(({
                            loading: false
                        }));
                });
        }
        const claimApply = getUrl(this.props.history.location.search);
        if(claimApply && claimApply.id) {
            this.setState({loading: true});
            claimApplieDetail(claimApply.id)
                .then(res => {
                    if(res.ok) {
                        const order = onChangeClaimApplyDetail(res.data);
                        const claimMaterialDetails = res.data.claimMaterialDetails;
                        const accessories = res.data.details;
                        const data = res.data;
                        getPartServicePrices({
                            repairDate: data.repairDate ? data.repairDate : data.checkDate,
                            brandId: data.brandId,
                            parts: claimMaterialDetails.map(v => v.usedPartId),
                            productCategoryCode: data.productCategoryCode,
                            accessories: accessories.map(v => v.usedPartId)
                        })
                            .then(res => {
                                if(res.ok)
                                    this.setState({
                                        loading: false,
                                        hasOperat: true,
                                        showClaimApply: false,
                                        data: Object.assign({}, this.state.data, {
                                            ...order,
                                            subClaimId: undefined,
                                            subClaimCode: undefined,
                                            subDealerId: data.subDealerId,
                                            subDealerCode: data.subDealerCode,
                                            subDealerName: data.subDealerName,
                                            // repairDate: data.repairDate ? data.repairDate : data.checkDate,
                                        }),
                                        claimWorkItemDetails: data.claimWorkItemDetails,
                                        claimAthDetails: data.claimAthDetails,
                                        claimMaterialDetails: claimMaterialDetails.map(item => {
                                            const partServicePrice = res.data.partPrices.find(v => v.partId === item.usedPartId);
                                            if(partServicePrice)
                                                return Object.assign({}, item, {
                                                    price: partServicePrice.price * partServicePrice.priceRate,
                                                    mgmtFee: item.mgmtRate ? item.quantity * partServicePrice.price * item.mgmtRate * partServicePrice.priceRate : 0,
                                                    materialFee: item.quantity * partServicePrice.price * partServicePrice.priceRate,
                                                    totalFee: (item.quantity * partServicePrice.price * partServicePrice.priceRate) +
                                                        (item.mgmtRate ? item.quantity * partServicePrice.price * item.mgmtRate * partServicePrice.priceRate : 0)
                                                });
                                            return item;
                                        }),
                                        details: accessories.map(item => {
                                            let quantity = 0;
                                            const accessory = res.data.accessoryPrices.find(v => v.partId === item.usedPartId);
                                            const tmpQuantity = item.usedQty > accessory.maxQty ? accessory.maxQty : item.usedQty;
                                            if(Number.isInteger(tmpQuantity / accessory.minPackSize))
                                                quantity = tmpQuantity;
                                            else quantity = (Math.ceil(tmpQuantity / accessory.minPackSize) * accessory.minPackSize) > accessory.maxQty
                                                ? accessory.maxQty : Math.ceil(tmpQuantity / accessory.minPackSize) * accessory.minPackSize;
                                            if(accessory)
                                                return Object.assign({}, item, {
                                                    price: accessory.price * accessory.priceRate,
                                                    materialFee: quantity * accessory.price * accessory.priceRate,
                                                    maxQty: accessory.maxQty || 0,
                                                    minPackSize: accessory.minPackSize || 0,
                                                    quantity
                                                });
                                            return item;
                                        })
                                    });
                                else
                                    this.setState(({
                                        hasOperat: true,
                                        loading: false
                                    }));
                            });
                        this.getClaimHistories(res.data.vin, res.data.createTime);
                        this.getWorkItems(res.data.productCategoryCode, res.data.brandId);
                    } else
                        this.setState(({
                            loading: false,
                            hasOperat: true,
                            showClaimApply: false
                        }));
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    // eslint-disable-next-line no-mixed-operators
    disabledDate = current => current && current > moment().startOf(1, 'day') || current < moment().add(-12, 'months');
    labelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }
    labelMapDutyUnit = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `${d.code}`;
        return '';
    }
    vehicleLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `${d.vin}`;
        return '';
    }
    getClaimHistories = (vin, createTime, claimId) => {
        this.setState({
            loading: true
        });
        getcClaimHistoriesList({
            vin,
            createTime,
            claimId
        })
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        claimHistories: res.data
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    getWorkItems = (productCategoryCode, brandId) => {
        this.setState({
            loading: true
        });
        getWorkItems({
            productCategoryCode,
            brandId
        })
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        workItem: res.data.content
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    getMgmtRates = brandId => {
        this.setState({
            loading: true
        });
        getMgmtRates({
            brandId
        })
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        mgmtRate: res.data.content
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    getPartCategory = value => {
        this.setState({
            loading: true
        });
        getPartCategory({
            faultType: value
        })
            .then(res => {
                if(res.ok) {
                    const partCategoryId = res.data.content.length > 0 ? res.data.content[0].id : '';
                    const materials = this.state.claimMaterialDetails;
                    const usedPart = materials.findIndex(v => v.isCaused === true);
                    if(usedPart !== -1 && usedPart.partCategoryId !== partCategoryId) {
                        const tmp = materials.map(item => {
                            if(item.isCaused === true)
                                return Object.assign({}, item, {
                                    isCaused: false
                                });
                            return item;
                        });
                        this.setState({
                            loading: false,
                            claimMaterialDetails: tmp,
                            hasOperat: true,
                            partCategoryId
                        });
                    } else
                        this.setState({
                            loading: false,
                            partCategoryId
                        });
                } else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    onChange = (value, name) => {
        if(name === 'faultType')
            this.getPartCategory(value);
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onChangeSwitch = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            currency: this.props.initEnum.brands.find(v => v.value === value).currency
        });
        this.setState({
            data,
            details: [],
            claimWorkItemDetails: [],
            hasOperat: true
        });
    }
    onChangeRepairType = (value, name) => {
        if(this.state.data.repairType !== undefined && this.state.data.repairType !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch1',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switchRepairType',
                    defaultMessage: '变更索赔类型，将会清空预授权单号数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchRepairType(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value
                }),
                hasOperat: true
            });
    }
    onChangeSwitchRepairType = (value, name) => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                [name]: value,
                claimApplyId: '',
                claimApplyCode: '',
                claimApplyCreateTime: undefined
            }),
            hasOperat: true
        });
    }
    onChangeBrand = (value, name) => {
        if(this.state.data.productCategoryCode && value)
            this.getWorkItems(this.state.data.productCategoryCode, value);
        this.getMgmtRates(value);
        if(this.state.data.brandId !== undefined && this.state.data.brandId !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switchBrandId',
                    defaultMessage: '变更品牌，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitch(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value,
                    currency: this.props.initEnum.brands.find(v => v.value === value).currency
                }),
                hasOperat: true
            });
    }
    
    onSelectPart = records => {
        const claimWorkItemDetails = this.state.claimWorkItemDetails || [];
        const claimMaterialDetails = this.state.claimMaterialDetails || [];
        this.onSelectClaimMaterial(records, claimWorkItemDetails, claimMaterialDetails);
    }
    onSelectClaimMaterial = (records, claimWorkItemDetails, claimMaterialDetails) => {
        const workItem = this.state.workItem;
        if(records.some(v => v.workItems.length === 0)) {
            records.forEach(r => {
                const indexMaterial = claimMaterialDetails.findIndex(v => v.usedPartId === r.id);
                if(indexMaterial === -1)
                    claimMaterialDetails.push({
                        isCaused: false,
                        usedPartId: r.id,
                        usedPartCode: r.code,
                        usedPartName: r.name,
                        newPartId: r.id,
                        newPartCode: r.code,
                        newPartName: r.name,
                        unit: r.unit,
                        price: r.price * r.priceRate,
                        quantity: 1,
                        materialFee: r.price * r.priceRate,
                        usedPartDealCategory: claimUsedPartDealCategory.销毁,
                        mgmtRate: r.mgmtFeeRate,
                        mgmtFee: r.mgmtFeeRate ? r.price * r.mgmtFeeRate * r.priceRate : 0,
                        priceRate: r.priceRate,
                        partCategoryId: r.partCategoryId,
                        isNeedPicture: r.isNeedPicture,
                        supplierId: r.supplierId,
                        supplierCode: r.supplierCode,
                        totalFee: (r.price * r.priceRate) + (r.mgmtFeeRate ? r.price * r.mgmtFeeRate * r.priceRate : 0),
                        partCategoryCode: r.partCategoryCode,
                        productCategoryCode: r.productCategoryCode,
                        faultType: r.faultType
                    });
                if(r.workItems.length < 1 && workItem)
                    claimWorkItemDetails.push({
                        id: uuid(),
                        usedPartId: r.id,
                        usedPartCode: r.code,
                        workItemId: workItem.id,
                        workItemCode: workItem.code,
                        workItemName: workItem.name,
                        laborHour: workItem.laborHour,
                        laborPrice: workItem.laborPrice,
                        laborFee: workItem.laborHour / 100 * workItem.laborPrice,
                        remark: workItem.remark,
                        isDefault: true,
                        productCategoryCode: workItem.productCategoryCode,
                        partProductCategoryCodes: r.productCategoryCode,
                        isCustomed: true
                    });
                else
                    r.workItems.forEach(v => {
                        const index = claimWorkItemDetails.findIndex(o => o.workItemId === v.id);
                        if(index === -1) {
                            claimWorkItemDetails.push({
                                id: uuid(),
                                usedPartId: r.id,
                                usedPartCode: r.code,
                                workItemId: v.id,
                                workItemCode: v.code,
                                workItemName: v.name,
                                laborHour: v.laborHour,
                                laborPrice: v.laborPrice,
                                laborFee: v.laborHour / 100 * v.laborPrice,
                                remark: v.remark,
                                productCategoryCode: v.productCategoryCode,
                                partProductCategoryCodes: r.productCategoryCode
                            });
                            v.assistWorkItems.forEach(o => {
                                const index = claimWorkItemDetails.findIndex(f => f.workItemId === o.id);
                                if(index === -1)
                                    claimWorkItemDetails.push({
                                        id: uuid(),
                                        usedPartId: r.id,
                                        usedPartCode: r.code,
                                        workItemId: o.id,
                                        workItemCode: o.code,
                                        workItemName: o.name,
                                        laborHour: o.laborHour,
                                        laborPrice: o.laborPrice,
                                        laborFee: o.laborHour / 100 * o.laborPrice,
                                        remark: o.remark,
                                        productCategoryCode: o.productCategoryCode,
                                        partProductCategoryCodes: r.productCategoryCode
                                    });
                            });
                        }
                    });
            });
            this.setState({
                claimWorkItemDetails: [...claimWorkItemDetails],
                claimMaterialDetails: [...claimMaterialDetails],
                hasOperat: true,
                showPartMultiSelectPanel: false
            });
        } else this.onSelectMaterials(records, claimWorkItemDetails, claimMaterialDetails);
    };
    onSelectMaterials = (records, claimWorkItemDetails, claimMaterialDetails) => {
        records.forEach(r => {
            const indexMaterial = claimMaterialDetails.findIndex(v => v.usedPartId === r.id);
            if(indexMaterial === -1)
                claimMaterialDetails.push({
                    isCaused: false,
                    usedPartId: r.id,
                    usedPartCode: r.code,
                    usedPartName: r.name,
                    newPartId: r.id,
                    newPartCode: r.code,
                    newPartName: r.name,
                    unit: r.unit,
                    price: r.price * r.priceRate,
                    quantity: 1,
                    materialFee: r.price * r.priceRate,
                    usedPartDealCategory: claimUsedPartDealCategory.销毁,
                    mgmtRate: r.mgmtFeeRate,
                    mgmtFee: r.mgmtFeeRate ? r.price * r.mgmtFeeRate * r.priceRate : 0,
                    priceRate: r.priceRate,
                    partCategoryId: r.partCategoryId,
                    isNeedPicture: r.isNeedPicture,
                    supplierId: r.supplierId,
                    supplierCode: r.supplierCode,
                    totalFee: (r.price * r.priceRate) + (r.mgmtFeeRate ? r.price * r.mgmtFeeRate * r.priceRate : 0),
                    partCategoryCode: r.partCategoryCode,
                    productCategoryCode: r.productCategoryCode,
                    faultType: r.faultType
                });
            r.workItems.forEach(v => {
                const index = claimWorkItemDetails.findIndex(o => o.workItemId === v.id);
                if(index === -1) {
                    claimWorkItemDetails.push({
                        id: uuid(),
                        usedPartId: r.id,
                        usedPartCode: r.code,
                        workItemId: v.id,
                        workItemCode: v.code,
                        workItemName: v.name,
                        laborHour: v.laborHour,
                        laborPrice: v.laborPrice,
                        laborFee: v.laborHour / 100 * v.laborPrice,
                        remark: v.remark,
                        productCategoryCode: v.productCategoryCode,
                        partProductCategoryCodes: r.productCategoryCode
                    });
                    v.assistWorkItems.forEach(o => {
                        const index = claimWorkItemDetails.findIndex(f => f.workItemId === o.id);
                        if(index === -1)
                            claimWorkItemDetails.push({
                                id: uuid(),
                                usedPartId: r.id,
                                usedPartCode: r.code,
                                workItemId: o.id,
                                workItemCode: o.code,
                                workItemName: o.name,
                                laborHour: o.laborHour,
                                laborPrice: o.laborPrice,
                                laborFee: o.laborHour / 100 * o.laborPrice,
                                remark: o.remark,
                                productCategoryCode: o.productCategoryCode,
                                partProductCategoryCodes: r.productCategoryCode
                            });
                    });
                }
            });
        });
        this.setState({
            claimWorkItemDetails: [...claimWorkItemDetails],
            claimMaterialDetails: [...claimMaterialDetails],
            hasOperat: true,
            showPartMultiSelectPanel: false
        });
    }
    onSelectPartAccessory = records => {
        const details = this.state.details || [];
        const detail = onSelectPartAccessory(records, details);
        this.setState({
            details: [...detail.details],
            hasOperat: true,
            showPartAssistPanel: false
        });
    }
    onClosePartAssistPanel = () => {
        this.setState({showPartAssistPanel: false});
    }
    onClosePartMultiSelectPanel = () => {
        this.setState({showPartMultiSelectPanel: false});
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const usedPartId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.usedPartId !== usedPartId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const newprops = this.props;
        const {data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails} = this.state;
        const isValid = newOrderValidator(data, claimWorkItemDetails, claimMaterialDetails, claimAthDetails);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        //政策校验
        const parts = [];
        claimMaterialDetails.map(v => parts.push(v.usedPartId));
        details.map(v => parts.push(v.usedPartId));
        getWarrantyPolicy({
            vehicleSoldId: data.vehicleSoldId,
            repairType: data.repairType,
            repairDate: data.repairDate,
            mileage: data.mileage,
            usedPartId: claimMaterialDetails.find(d => d.isCaused === true).usedPartId,
            brandId: data.brandId,
            subDealerId: data.subDealerId,
            claimApplyId: data.claimApplyId,
            dealerId: data.dealerId,
            id: data.id,
            isAddOrUpdate: true,
            parts
        })
            .then(res => {
                if(res.ok)
                    if(res.data.content)
                        Modal.confirm({
                            title: this.props.intl.formatMessage({
                                id: 'newPanel.message.switch1',
                                defaultMessage: '提示'
                            }),
                            content: res.data.content + this.props.intl.formatMessage({
                                id: 'newPanel.message.submit',
                                defaultMessage: '，是否继续操作？'
                            }),
                            onOk: () => this.onChangeSwitchonSubmit(data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, newprops),
                            onCancel: () => this.setState({loading: false})
                        });
                    else
                        newprops.onSubmit(data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, false).then(r => {
                            if(r.ok)
                                newprops.successReturn();
                            if(!this.isunmount)
                                this.setState({loading: false});
                        });
                else
                    this.setState({loading: false});
            });
    }
    onChangeSwitchonSubmit = (data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, newprops) => {
        newprops.onSubmit(data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, false).then(r => {
            if(r.ok)
                newprops.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitAndPreserve = () => {
        const newprops = this.props;
        const {data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails} = this.state;
        const isValid = newOrUpdateOrderValidator(data, claimWorkItemDetails, claimMaterialDetails, claimAthDetails);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        //政策校验
        const parts = [];
        claimMaterialDetails.map(v => parts.push(v.usedPartId));
        details.map(v => parts.push(v.usedPartId));
        getWarrantyPolicy({
            vehicleSoldId: data.vehicleSoldId,
            repairType: data.repairType,
            repairDate: data.repairDate,
            mileage: data.mileage,
            usedPartId: claimMaterialDetails.find(d => d.isCaused === true).usedPartId,
            brandId: data.brandId,
            subDealerId: data.subDealerId,
            claimApplyId: data.claimApplyId,
            dealerId: data.dealerId,
            id: data.id,
            isAddOrUpdate: true,
            parts
        })
            .then(res => {
                if(res.ok)
                    if(res.data.content)
                        Modal.confirm({
                            title: this.props.intl.formatMessage({
                                id: 'newPanel.message.switch1',
                                defaultMessage: '提示'
                            }),
                            content: res.data.content + this.props.intl.formatMessage({
                                id: 'newPanel.message.submit',
                                defaultMessage: '，是否继续操作？'
                            }),
                            onOk: () => this.onChangeSwitchonSubmitAndPreserve(data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, newprops),
                            onCancel: () => this.setState({loading: false})
                        });
                    else
                        newprops.onSubmit(data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, true).then(r => {
                            if(r.ok)
                                newprops.successReturn();
                            if(!this.isunmount)
                                this.setState({loading: false});
                        });
                else
                    this.setState({loading: false});
            });
    }
    onChangeSwitchonSubmitAndPreserve = (data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, newprops) => {
        newprops.onSubmit(data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, true).then(r => {
            if(r.ok)
                newprops.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onUpdateUsedQty = (usedQty, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.usedPartId === id) {
                let quantity = 0;
                const tmpQuantity = usedQty > d.maxQty ? d.maxQty : usedQty;
                if(Number.isInteger(tmpQuantity / d.minPackSize))
                    quantity = tmpQuantity;
                else quantity = (Math.ceil(tmpQuantity / d.minPackSize) * d.minPackSize) > d.maxQty
                    ? d.maxQty : Math.ceil(tmpQuantity / d.minPackSize) * d.minPackSize;
                return Object.assign({}, d, {
                    usedQty,
                    materialFee: d.price * quantity,
                    quantity
                });
            }
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onClickAddAccessoryBtn = e => {
        e.stopPropagation();
        if(!this.state.data.brandId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brandId',
                defaultMessage: '请先选择品牌'
            }));
        if(!this.state.data.vehicleSoldId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.vehicleSoldId1',
                defaultMessage: '请先选择车辆'
            }));
        if(!this.state.data.repairDate)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.repairDate',
                defaultMessage: '请先选择维修日期'
            }));
        this.setState({
            showPartAssistPanel: true,
            isAccessory: true
        });
    }
    onClickAddBtn = e => {
        e.stopPropagation();
        if(!this.state.data.brandId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brandId',
                defaultMessage: '请先选择品牌'
            }));
        if(!this.state.data.vehicleSoldId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.vehicleSoldId1',
                defaultMessage: '请先选择车辆'
            }));
        if(!this.state.data.repairDate)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.repairDate',
                defaultMessage: '请先选择维修日期'
            }));
        this.setState({
            showPartMultiSelectPanel: true,
            isAccessory: false
        });
    }
    onSelectClaimApply = data => {
        this.setState({
            loading: true
        });
        claimApplieDetail(data.id)
            .then(res => {
                if(res.ok) {
                    const order = onChangeClaimApplyDetail(res.data);
                    const claimMaterialDetails = res.data.claimMaterialDetails;
                    const accessories = res.data.details;
                    const data = res.data;
                    getPartServicePrices({
                        repairDate: data.repairDate ? data.repairDate : data.checkDate,
                        brandId: data.brandId,
                        parts: claimMaterialDetails.map(v => v.usedPartId),
                        productCategoryCode: data.productCategoryCode,
                        accessories: accessories.map(v => v.usedPartId)
                    })
                        .then(res => {
                            if(res.ok)
                                this.setState({
                                    loading: false,
                                    hasOperat: true,
                                    showClaimApply: false,
                                    data: Object.assign({}, this.state.data, {
                                        ...order,
                                        subClaimId: undefined,
                                        subClaimCode: undefined,
                                        repairDate: data.repairDate ? data.repairDate : data.checkDate,
                                    }),
                                    claimWorkItemDetails: data.claimWorkItemDetails,
                                    claimAthDetails: data.claimAthDetails,
                                    claimMaterialDetails: claimMaterialDetails.map(item => {
                                        const partServicePrice = res.data.partPrices.find(v => v.partId === item.usedPartId);
                                        if(partServicePrice)
                                            return Object.assign({}, item, {
                                                price: partServicePrice.price * partServicePrice.priceRate,
                                                mgmtFee: item.mgmtRate ? item.quantity * partServicePrice.price * item.mgmtRate * partServicePrice.priceRate : 0,
                                                materialFee: item.quantity * partServicePrice.price * partServicePrice.priceRate,
                                                totalFee: (item.quantity * partServicePrice.price * partServicePrice.priceRate) +
                                                    (item.mgmtRate ? item.quantity * partServicePrice.price * item.mgmtRate * partServicePrice.priceRate : 0)
                                            });
                                        return item;
                                    }),
                                    details: accessories.map(item => {
                                        let quantity = 0;
                                        const accessory = res.data.accessoryPrices.find(v => v.partId === item.usedPartId);
                                        const tmpQuantity = item.usedQty > accessory.maxQty ? accessory.maxQty : item.usedQty;
                                        if(Number.isInteger(tmpQuantity / accessory.minPackSize))
                                            quantity = tmpQuantity;
                                        else quantity = (Math.ceil(tmpQuantity / accessory.minPackSize) * accessory.minPackSize) > accessory.maxQty
                                            ? accessory.maxQty : Math.ceil(tmpQuantity / accessory.minPackSize) * accessory.minPackSize;
                                        if(accessory)
                                            return Object.assign({}, item, {
                                                price: accessory.price * accessory.priceRate,
                                                materialFee: quantity * accessory.price * accessory.priceRate,
                                                maxQty: accessory.maxQty || 0,
                                                minPackSize: accessory.minPackSize || 0,
                                                quantity
                                            });
                                        return item;
                                    })
                                });
                            else
                                this.setState(({
                                    hasOperat: true,
                                    loading: false
                                }));
                        });
                    this.getClaimHistories(res.data.vin, res.data.createTime);
                    this.getWorkItems(res.data.productCategoryCode, res.data.brandId);
                } else
                    this.setState(({
                        loading: false,
                        hasOperat: true,
                        showClaimApply: false
                    }));
            });
    }
    onClickClaimApply = () => {
        if(!this.state.data.vehicleSoldId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.vehicleSoldId',
                defaultMessage: '请先选择车辆档案'
            }));
        if(!this.state.data.repairType)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.repairType',
                defaultMessage: '请先选择索赔类型'
            }));
        this.setState({showClaimApply: true});
    }
    onCloseClaimApply = () => {
        this.setState({showClaimApply: false});
    }
    onSelectSubClaim = data => {
        subClaimDetail(data.id)
            .then(res => {
                if(res.ok) {
                    const order = onChangeSubClaimDetail(res.data);
                    const data = res.data;
                    getPartServicePrices({
                        repairDate: data.repairDate ? data.repairDate : data.checkDate,
                        brandId: data.brandId,
                        parts: data.claimMaterialDetails.map(v => v.usedPartId),
                        productCategoryCode: data.productCategoryCode,
                        accessories: data.details.map(v => v.usedPartId)
                    })
                        .then(res => {
                            if(res.ok)
                                this.setState({
                                    loading: false,
                                    hasOperat: true,
                                    showSubClaim: false,
                                    data: Object.assign({}, this.state.data, {
                                        ...order,
                                        repairDate: data.repairDate ? data.repairDate : data.checkDate,
                                    }),
                                    claimWorkItemDetails: data.claimWorkItemDetails,
                                    claimAthDetails: data.claimAthDetails,
                                    claimMaterialDetails: data.claimMaterialDetails.map(item => {
                                        const partServicePrice = res.data.partPrices.find(v => v.partId === item.usedPartId);
                                        if(partServicePrice)
                                            return Object.assign({}, item, {
                                                price: partServicePrice.price * partServicePrice.priceRate,
                                                mgmtFee: item.mgmtRate ? item.quantity * partServicePrice.price * item.mgmtRate * partServicePrice.priceRate : 0,
                                                materialFee: item.quantity * partServicePrice.price * partServicePrice.priceRate,
                                                totalFee: (item.quantity * partServicePrice.price * partServicePrice.priceRate) +
                                                    (item.mgmtRate ? item.quantity * partServicePrice.price * item.mgmtRate * partServicePrice.priceRate : 0)
                                            });
                                        return item;
                                    }),
                                    details: data.details.map(item => {
                                        let quantity = 0;
                                        const accessory = res.data.accessoryPrices.find(v => v.partId === item.usedPartId);
                                        const tmpQuantity = item.usedQty > accessory.maxQty ? accessory.maxQty : item.usedQty;
                                        if(Number.isInteger(tmpQuantity / accessory.minPackSize))
                                            quantity = tmpQuantity;
                                        else quantity = (Math.ceil(tmpQuantity / accessory.minPackSize) * accessory.minPackSize) > accessory.maxQty
                                            ? accessory.maxQty : Math.ceil(tmpQuantity / accessory.minPackSize) * accessory.minPackSize;
                                        if(accessory)
                                            return Object.assign({}, item, {
                                                price: accessory.price * accessory.priceRate,
                                                materialFee: quantity * accessory.price * accessory.priceRate,
                                                maxQty: accessory.maxQty,
                                                minPackSize: accessory.minPackSize,
                                                quantity
                                            });
                                        return item;
                                    })
                                });
                            else
                                this.setState(({
                                    hasOperat: true,
                                    loading: false
                                }));
                        });
                    this.getClaimHistories(res.data.vin, res.data.createTime);
                    this.getWorkItems(res.data.productCategoryCode, res.data.brandId);
                } else
                    this.setState(({
                        loading: false,
                        hasOperat: true,
                        showSubClaim: false
                    }));
            });
    }
    onClickSubClaim = () => {
        if(!this.state.data.vehicleSoldId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.vehicleSoldId',
                defaultMessage: '请先选择车辆档案'
            }));
        if(!this.state.data.repairType)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.repairType',
                defaultMessage: '请先选择索赔类型'
            }));
        this.setState({showSubClaim: true});
    }
    onCloseSubClaim = () => {
        this.setState({showSubClaim: false});
    }
    onSearchFaultMode = value =>
        faultModeQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            });
    onSelectFaultMode = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                faultModeId: data.id,
                faultModeCode: data.code,
                faultModeName: data.name
            }),
            hasOperat: true,
            showFaultMode: false
        });
    }
    onClickFaultMode = () => {
        this.setState({showFaultMode: true});
    }
    onCloseFaultMode = () => {
        this.setState({showFaultMode: false});
    }
    onSearchDutyUnit = value =>
        getDutyUnitsQuickly({
            filter: value,
            type: dutyUnitType.索赔供应商,
            brandId: this.state.data.brandId,
            // partId: this.state.claimMaterialDetails.find(v => v.isCaused === true).usedPartId
        })
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            });
    onSelectDutyUnit = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                supplierId: data.id,
                supplierCode: data.code,
                supplierName: data.name,
                isNeedPictureSupplier: data.isNeedPicture
            }),
            showDutyUnit: false,
            hasOperat: true
        });
    }
    onClickDutyUnit = () => {
        this.setState({showDutyUnit: true});
    }
    onCloseDutyUnit = () => {
        this.setState({showDutyUnit: false});
    }
    onSearchVehicle = value => getVehicleSoldsQuickly({
        filter: value,
        isDealer: true,
        isOtherArea: this.state.data.isOtherArea
    })
        .then(res => {
            const data = res.data;
            if(data)
                return data.content;
        });
    onSelectVehicle = data => {
        if(!data.shipDate)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.shipDate1',
                defaultMessage: 'VIN为'
            }) + data.vin + this.props.intl.formatMessage({
                id: 'newPanel.message.shipDate2',
                defaultMessage: '的车辆缺少发车日期，请联系相关人员确认。'
            }));
        if(data.productCategoryCode && this.state.data.brandId)
            this.getWorkItems(data.productCategoryCode, this.state.data.brandId);
        if(this.state.data.brandId)
            this.getMgmtRates(this.state.data.brandId);
        this.getClaimHistories(data.vin, this.props.id ? data.createTime : dateTime);
        if(this.state.data.claimApplyId !== undefined && this.state.data.vehicleSoldId !== data.id)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch1',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switchVehicleSoldId',
                    defaultMessage: '变更车辆档案，将会清空索赔类型和预授权单号，是否变更？'
                }),
                onOk: () => this.onChangeSwitchVehicle(data)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    vehicleSoldId: data.id,
                    vin: data.vin,
                    mileage: undefined,
                    engineCode: data.engineCode,
                    saleDate: data.saleDate,
                    shippingDate: data.shippingDate,
                    customerName: data.customerName,
                    cellPhoneNumber: data.cellPhoneNumber,
                    vehicleStatus: data.status,
                    repairType: undefined,
                    transmissionSn: data.transmissionSn,
                    productCategoryCode: data.productCategoryCode,
                    productCategoryName: data.productCategoryName,
                    annoucementNumber: data.annoucementNumber,
                    customerSoldType: data.customerSoldType,
                    isKD: data.isKD,
                    currency: data.currency,
                    wholesaleDealerId: data.wholesaleDealerId,
                    wholesaleDealerCode: data.wholesaleDealerCode,
                    wholesaleDealerName: data.wholesaleDealerName,
                    country: data.country,
                    shipDate: data.shipDate,
                    companyName: data.companyName,
                    address: data.address,
                    email: data.email,
                    subDealerCode: data.salesDealerCode,
                    isNeedPictureDealer: data.isNeedPicture,
                    productionDate: data.productionDate
                }),
                showVehicle: false,
                hasOperat: true
            });
    }
    onChangeSwitchVehicle = vehicle => {
        const data = onChangeSwitchVehicle(vehicle, this.state.data);
        this.setState({
            data: data.vehicle,
            details: [],
            claimWorkItemDetails: [],
            claimMaterialDetails: [],
            showVehicle: false,
            hasOperat: true
        });
    }
    onClickVehicle = e => {
        e.stopPropagation();
        this.setState({showVehicle: true});
    }
    onCloseVehicle = () => {
        this.setState({showVehicle: false});
    }
    onPartQuantityChange = (usedPartId, value) => {
        const materials = this.state.claimMaterialDetails;
        const tmp = materials.map(item => {
            if(item.usedPartId === usedPartId)
                return Object.assign({}, item, {
                    quantity: value,
                    mgmtFee: item.mgmtRate ? value * item.price * item.mgmtRate : 0,
                    materialFee: value * item.price,
                    totalFee: (value * item.price) + (item.mgmtRate ? value * item.price * item.mgmtRate : 0)
                });
            return item;
        });
        this.setState({
            claimMaterialDetails: tmp,
            hasOperat: true
        });
    };
    onSelectParts = (usedPartId, value) => {
        const materials = this.state.claimMaterialDetails;
        const tmp = materials.map(item => {
            if(item.usedPartId === usedPartId)
                return Object.assign({}, item, {
                    newPartId: value.id,
                    newPartCode: value.code,
                    newPartName: value.name
                });
            return item;
        });
        this.setState({
            claimMaterialDetails: tmp,
            hasOperat: true
        });
    };
    onCausedCheck = e => {
        // if(!this.state.data.faultType)
        //     return msg.warn(this.props.intl.formatMessage({
        //         id: 'newPanel.message.faultType',
        //         defaultMessage: '请先选择故障类型'
        //     }));
        const materials = this.state.claimMaterialDetails;
        const usedPart = this.state.claimMaterialDetails.findIndex(v => v.isCaused === true);
        if(e.target.checked === true && usedPart !== -1)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.isCaused',
                defaultMessage: '已经存在主损件，请先取消已有的主损件！'
            }));
        const material = materials.find(v => v.usedPartId === e.target.id);
        // if(e.target.checked === true && material.partCategoryId !== this.state.partCategoryId)
        //     return msg.warn(this.props.intl.formatMessage({
        //         id: 'newPanel.message.partCategoryId',
        //         defaultMessage: '备件分类与故障类型不一致，不允许为主损件，请重新选择主损件。'
        //     }));
        const isCaused = e.target.checked;
        if(isCaused)
            this.setState({
                data: Object.assign({}, this.state.data, {
                    supplierId: material.supplierId,
                    supplierCode: material.supplierCode,
                    faultType: material.faultType
                })
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    supplierId: '',
                    supplierCode: '',
                    supplierName: '',
                    isNeedPictureSupplier: undefined
                })
            });
        const tmp = materials.map(item => {
            if(item.usedPartId === e.target.id)
                return Object.assign({}, item, {
                    isCaused
                });
            return item;
        });
        this.setState({
            claimMaterialDetails: tmp,
            hasOperat: true
        });
    };
    onDeleteAllParts = () => {
        this.setState({
            claimWorkItemDetails: [],
            claimMaterialDetails: [],
            details: [],
            hasOperat: true
        });
    };
    onDeletePart = usedPartId => {
        const materials = this.state.claimMaterialDetails;
        const tmpParts = materials.filter(m => m.usedPartId !== usedPartId);
        this.setState({
            claimMaterialDetails: [...tmpParts],
            hasOperat: true
        });
        const newDetails = this.state.claimWorkItemDetails.filter(d => d.usedPartId !== usedPartId);
        //删除辅料
        const accessoryDetails = this.state.details || [];
        const tmp = accessoryDetails.filter(d => d.partId !== usedPartId);
        this.setState({
            claimWorkItemDetails: [...newDetails],
            details: [...tmp],
            hasOperat: true
        });
    };
    onChangeUploadPhoto = (data, type) => {
        const claimAthDetails = this.state.claimAthDetails || [];
        const index = claimAthDetails.findIndex(v => v.type === type && v.fileType === fileType.图片);
        const attachmentsTmp = [];
        attachmentsTmp.push({
            fileId: data.id,
            fileName: data.fileName
        });
        if(index === -1) {
            claimAthDetails.push({
                type,
                fileType: fileType.图片,
                attachments: attachmentsTmp
            });
            this.setState({
                claimAthDetails: [...claimAthDetails],
                hasOperat: true
            });
        } else {
            const tmp = claimAthDetails.map(d => {
                if(d.type === type && d.fileType === fileType.图片)
                    return Object.assign({}, d, {
                        attachments: d.attachments.concat(attachmentsTmp)
                    });
                return d;
            });
            this.setState({
                claimAthDetails: tmp,
                hasOperat: true
            });
        }
    }
    onRemovePhoto = (data, type) => {
        const claimAthDetails = this.state.claimAthDetails || EMPTY_ARRAY;
        let attachments = EMPTY_ARRAY;
        const tmp = claimAthDetails.map(d => {
            if(d.type === type && d.fileType === fileType.图片) {
                attachments = d.attachments || EMPTY_ARRAY;
                attachments.splice({
                    fileId: data.id,
                    fileName: data.name
                }, 1);
                return Object.assign({}, d, {
                    attachments: [...attachments]
                });
            }
            return d;
        });
        this.setState({
            claimAthDetails: tmp,
            hasOperat: true
        });
    }
    onChangeUploadFile = (data, type) => {
        const claimAthDetails = this.state.claimAthDetails || [];
        const index = claimAthDetails.findIndex(v => v.type === type && v.fileType === fileType.文件);
        const attachmentsTmp = [];
        attachmentsTmp.push({
            fileId: data.id,
            fileName: data.fileName
        });
        if(index === -1) {
            claimAthDetails.push({
                type,
                fileType: fileType.文件,
                attachments: attachmentsTmp
            });
            this.setState({
                claimAthDetails: [...claimAthDetails],
                hasOperat: true
            });
        } else {
            const tmp = claimAthDetails.map(d => {
                if(d.type === type && d.fileType === fileType.文件)
                    return Object.assign({}, d, {
                        attachments: d.attachments.concat(attachmentsTmp)
                    });
                return d;
            });
            this.setState({
                claimAthDetails: tmp,
                hasOperat: true
            });
        }
    }
    onRemoveFile = (data, type) => {
        const claimAthDetails = this.state.claimAthDetails || EMPTY_ARRAY;
        let attachments = EMPTY_ARRAY;
        const tmp = claimAthDetails.map(d => {
            if(d.type === type && d.fileType === fileType.文件) {
                attachments = d.attachments || EMPTY_ARRAY;
                attachments.splice({
                    fileId: data.id,
                    fileName: data.name
                }, 1);
                return Object.assign({}, d, {
                    attachments: [...attachments]
                });
            }
            return d;
        });
        this.setState({
            claimAthDetails: tmp,
            hasOperat: true
        });
    }
    onDeleteWorkItem = id => {
        const details = this.state.claimWorkItemDetails.filter(d => d.id !== id);
        this.setState({
            claimWorkItemDetails: [...details],
            hasOperat: true
        });
    };
    onDeleteAllWorkItem = ids => {
        const details = this.state.claimWorkItemDetails.filter(d => !ids.includes(d.id));
        this.setState({
            claimWorkItemDetails: [...details],
            hasOperat: true
        });
    };
    onSelectFaultItem = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                faultItemId: data.id,
                faultItemCode: data.code,
                faultItemName: `${data.categoryL1Name}-${data.categoryL2Name}-${data.name}`,
                faultItemCnName: data.cnName,
                faultItemNameData: data.cnName === '其他' ? data.name : ''
            }),
            hasOperat: true
        });
    }
    onIsOtherAreaCheck = e => {
        const isOtherArea = e.target.checked;
        if(this.state.data.vehicleSoldId)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.isOtherArea',
                    defaultMessage: '变更是否跨区域索赔，将会清空车辆相关数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchIsOtherArea(isOtherArea)
            });
        else {
            const data = Object.assign({}, this.state.data, {
                isOtherArea
            });
            this.setState({
                data,
                hasOperat: true
            });
        }
    }
    onChangeSwitchIsOtherArea = isOtherArea => {
        const data = onChangeSwitchVehicleIsOtherArea(isOtherArea, this.state.data);
        this.setState({
            data: data.vehicle,
            details: [],
            claimWorkItemDetails: [],
            hasOperat: true
        });
    }
    onClickAddWorkItem = e => {
        e.stopPropagation();
        const {claimMaterialDetails} = this.state;
        if(!claimMaterialDetails.some(d => d.isCaused === true))
            return msg.warning(this.props.intl.formatMessage({
                id: 'validator.message.isCaused',
                defaultMessage: '请选择一个材料为主损件'
            }));
        this.setState({showWorkItem: true});
    }
    onCloseWorkItem = () => {
        this.setState({showWorkItem: false});
    }
    onSelectWorkItem = records => {
        const {claimMaterialDetails, claimWorkItemDetails} = this.state;
        const claimMaterialDetail = claimMaterialDetails.find(v => v.isCaused === true);
        records.forEach(r => {
            const index = claimWorkItemDetails.findIndex(o => o.workItemId === r.id);
            if(index === -1)
                claimWorkItemDetails.push({
                    id: uuid(),
                    usedPartId: claimMaterialDetail.usedPartId,
                    usedPartCode: claimMaterialDetail.usedPartCode,
                    workItemId: r.id,
                    workItemCode: r.code,
                    workItemName: r.name,
                    laborHour: r.laborHour,
                    laborPrice: r.laborPrice,
                    laborFee: r.laborHour / 100 * r.laborPrice,
                    remark: r.remark,
                    productCategoryCode: r.productCategoryCode,
                    partProductCategoryCodes: claimMaterialDetail.productCategoryCode,
                    isCustomed: true
                });
        });
        this.setState({
            claimWorkItemDetails: [...claimWorkItemDetails],
            hasOperat: true,
            showWorkItem: false
        });
    }
    onChangeRepairDate = (value, name) => {
        const {data, details, claimMaterialDetails} = this.state;
        if(data.repairDate && data.brandId && (claimMaterialDetails.length > 0 || details.length > 0)) {
            this.setState({
                loading: true
            });
            getPartServicePrices({
                repairDate: data.repairDate,
                brandId: data.brandId,
                parts: claimMaterialDetails.map(v => v.usedPartId),
                productCategoryCode: data.ProductCategoryCode,
                accessories: details.map(v => v.usedPartId)
            })
                .then(res => {
                    if(res.ok)
                        this.setState({
                            data: Object.assign({}, this.state.data, {
                                [name]: value
                            }),
                            claimMaterialDetails: claimMaterialDetails.map(item => {
                                const partServicePrice = res.data.partPrices.find(v => v.partId === item.usedPartId);
                                if(partServicePrice)
                                    return Object.assign({}, item, {
                                        price: partServicePrice.price * partServicePrice.priceRate,
                                        mgmtFee: item.mgmtRate ? item.quantity * partServicePrice.price * item.mgmtRate * partServicePrice.priceRate : 0,
                                        materialFee: item.quantity * partServicePrice.price * partServicePrice.priceRate,
                                        totalFee: (item.quantity * partServicePrice.price * partServicePrice.priceRate) +
                                            (item.mgmtRate ? item.quantity * partServicePrice.price * item.mgmtRate * partServicePrice.priceRate : 0)
                                    });
                                return item;
                            }),
                            details: details.map(item => {
                                let quantity = 0;
                                const accessory = res.data.accessoryPrices.find(v => v.partId === item.usedPartId);
                                const tmpQuantity = item.usedQty > accessory.maxQty ? accessory.maxQty : item.usedQty;
                                if(Number.isInteger(tmpQuantity / accessory.minPackSize))
                                    quantity = tmpQuantity;
                                else quantity = (Math.ceil(tmpQuantity / accessory.minPackSize) * accessory.minPackSize) > accessory.maxQty
                                    ? accessory.maxQty : Math.ceil(tmpQuantity / accessory.minPackSize) * accessory.minPackSize;
                                if(accessory)
                                    return Object.assign({}, item, {
                                        price: accessory.price * accessory.priceRate,
                                        materialFee: quantity * accessory.price * accessory.priceRate,
                                        maxQty: accessory.maxQty,
                                        minPackSize: accessory.minPackSize,
                                        quantity
                                    });
                                return item;
                            }),
                            loading: false,
                            hasOperat: true
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
        this.setState({
            data: Object.assign({}, this.state.data, {
                [name]: value
            }),
            hasOperat: true
        });
    }
    onClickFaultItemBtn = () => {
        this.setState({
            isFaultItem: !this.state.isFaultItem
        });
    }
    onClickStopPropagation = e => {
        e.stopPropagation();
    }
    onWorkItemLaborHourChange = (id, value) => {
        const claimWorks = this.state.claimWorkItemDetails;
        const tmp = claimWorks.map(item => {
            if(item.id === id)
                return Object.assign({}, item, {
                    laborHour: value,
                    laborFee: value / 100 * item.laborPrice
                });
            return item;
        });
        this.setState({
            claimWorkItemDetails: tmp,
            hasOperat: true
        });
    };
    onSelectDealer = data => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                subDealerId: data.id,
                subDealerCode: data.code,
                subDealerName: data.name,
            }),
            hasOperat: true
        });
    }
    onClickSupplierBtn = () => {
        this.setState({
            isSupplier: !this.state.isSupplier
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading, claimWorkItemDetails, claimMaterialDetails, claimHistories, claimApprovedHis} = this.state;
        const partIds = claimMaterialDetails.map(v => v.usedPartId);
        const faultModeInfo = data.faultModeId ? {
            id: data.faultModeId,
            code: data.faultModeCode,
            name: data.faultModeName,
        } : null;
        const dutyUnitInfo = data.supplierId ? {
            id: data.supplierId,
            code: data.supplierCode,
            name: data.supplierName,
        } : null;
        const vehicleInfo = data.vehicleSoldId ? {
            id: data.vehicleSoldId,
            vin: data.vin
        } : null;
        const faultItemInfo = data.faultItemId ? {
            id: data.faultItemId,
            code: data.faultItemCode,
            name: data.faultItemName,
        } : null;
        const dealerInfo = data.subDealerId ? {
            id: data.subDealerId,
            code: data.subDealerCode,
            name: data.subDealerName
        } : null;
        const validateFaultMode = !data.faultModeId && this.state.validate ? 'error' : null;
        const validateRepairType = !data.repairType && this.state.validate ? 'error' : null;
        const validatePartPurchasedDate = !data.partPurchasedDate && this.state.validate ? 'error' : null;
        const validateRepairCode = !data.repairCode && this.state.validate ? 'error' : null;
        const validateRepairDate = !data.repairDate && this.state.validate ? 'error' : null;
        const validateVehicle = !data.vehicleSoldId && this.state.validate ? 'error' : null;
        const validateBrandId = !data.brandId && this.state.validate ? 'error' : null;
        const validateFaultType = !data.faultType && this.state.validate ? 'error' : null;
        const validateFaultItem = !data.faultItemId && this.state.validate ? 'error' : null;
        const validateClaimApplyId = data.isOtherArea && !data.claimApplyId && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions);
        if(this.props.initEnum.brands.length === 1 && !this.props.id) {
            data.brandId = this.props.initEnum.brands[0].value;
            data.brandName = this.props.initEnum.brands[0].text;
            data.currency = this.props.initEnum.brands[0].currency;
        }
        //工时费
        let laborFee = 0;
        //材料费
        let materialFee = 0;
        //管理费
        let mgmtFee = 0;
        //辅料费
        let assistantFee = 0;
        //费用合计
        let totalFee = 0;

        if(claimWorkItemDetails)
            claimWorkItemDetails.forEach(d => {
                laborFee += (d.laborFee);
            });
        if(claimMaterialDetails)
            claimMaterialDetails.forEach(d => {
                materialFee += (d.materialFee);
                mgmtFee += d.mgmtFee;
            });
        if(details)
            details.forEach(d => {
                assistantFee += (d.materialFee);
            });
        totalFee = laborFee + materialFee + mgmtFee + assistantFee;
        const colums = [{
            title: formatMessage({
                id: 'newPanel.usedPartCode',
                defaultMessage: '旧件编号'
            }),
            dataIndex: 'usedPartCode'
        },
        {
            title: formatMessage({
                id: 'newPanel.usedPartName',
                defaultMessage: '旧件名称'
            }),
            dataIndex: 'usedPartName'
        },
        {
            title: formatMessage({
                id: 'newPanel.usedPartDealCategory',
                defaultMessage: '旧件处理政策'
            }),
            dataIndex: 'usedPartDealCategory',
            render: text => conventEnumValueToString(claimUsedPartDealCategory, text)
        },
        {
            title: formatMessage({
                id: 'newPanel.unit',
                defaultMessage: '计量单位'
            }),
            dataIndex: 'unit'
        },
        {
            title: formatMessage({
                id: 'newPanel.usedQty',
                defaultMessage: '索赔用量'
            }),
            dataIndex: 'usedQty',
            render: (text, record) => {
                const validate = (text === null || text === undefined) ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <LocalizeInputNumber
                            min={0}
                            id={record.usedPartId}
                            precision={2}
                            value={text} onBlur={this.onUpdateUsedQty}/>
                    </FormItem>
                );
            }
        },
        {
            title: formatMessage({
                id: 'newPanel.quantity',
                defaultMessage: '计价数量'
            }),
            dataIndex: 'quantity'
        }, {
            title: details && details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'newPanel.column.allDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'newPanel.column.empty',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : <a>{formatMessage({
                    id: 'newPanel.column.empty',
                    defaultMessage: '清空'
                })}</a>,
            dataIndex: 'usedPartId',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'newPanel.column.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        if(!this.props.isMoneyVisible)
            colums.splice(6, 0,
                {
                    title: formatMessage({
                        id: 'newPanel.price',
                        defaultMessage: '单价'
                    }),
                    dataIndex: 'price',
                    render: text => formatAmount(text)
                },
                {
                    title: formatMessage({
                        id: 'newPanel.materialFee',
                        defaultMessage: '材料费合计'
                    }),
                    dataIndex: 'materialFee',
                    render: text => formatAmount(text)
                });
        const columResults = [{
            title: formatMessage({
                id: 'newPanel.approverName',
                defaultMessage: '审核人'
            }),
            dataIndex: 'approverName'
        },
        {
            title: formatMessage({
                id: 'newPanel.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment'
        },
        {
            title: formatMessage({
                id: 'newPanel.approvedResult',
                defaultMessage: '审核结果'
            }),
            dataIndex: 'approveResult'
        },
        {
            title: formatMessage({
                id: 'newPanel.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }];
        const supplierComp = data.brandId && claimMaterialDetails.some(v => v.isCaused === true)
            ? (<div onClick={this.onClickStopPropagation}>{this.state.isSupplier ? <TextInput
                name="supplierCode"
                value={data.supplierCode}
                onBlur={this.onChange} /> : <SearchSelect
                value={dutyUnitInfo}
                placeholder={this.props.intl.formatMessage({
                    id: 'newPanel.form.supplierId.placeholder',
                    defaultMessage: '请输入供应商名称或编号进行查询'
                })}
                onSelect={this.onSelectDutyUnit}
                onSearch={this.onSearchDutyUnit}
                keyIndex="id"
                labelMap={this.labelMapDutyUnit}
                onClickSearchBtn={this.onClickDutyUnit} />}</div>) : (<TextInput name="supplierId"
                value={''} disabled placeholder={this.props.intl.formatMessage({
                    id: 'newPanel.dealerComp.placeholder',
                    defaultMessage: '请先选择品牌和主损件'
                })} />);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Anchor className={styles.toc_affix}
                        showInkInFixed={true}>
                        <Link href={`${location.hash}#components-anchor-common`} title={this.props.intl.formatMessage({
                            id: 'newPanel.anchor.common',
                            defaultMessage: '基本信息'
                        })} />
                        <Link href={`${location.hash}#components-anchor-vehicleInfo`} title={this.props.intl.formatMessage({
                            id: 'newPanel.anchor.vehicleInfo',
                            defaultMessage: '车辆信息'
                        })} />
                        <Link href={`${location.hash}#components-anchor-material`} title={this.props.intl.formatMessage({
                            id: 'newPanel.anchor.material',
                            defaultMessage: '材料信息'
                        })} />
                        {!data.isOtherArea && <Link href={`${location.hash}#components-anchor-claimHistory`} title={this.props.intl.formatMessage({
                            id: 'newPanel.anchor.claimHistory',
                            defaultMessage: '历史索赔'
                        })} />}
                    </Anchor>
                    <Collapse defaultActiveKey={['1', '2']} className={styles.collapseMarginTop}>
                        <Panel id="components-anchor-common" key="1" header={<Row><Col {...PANEL_CARD_COL_SPAN}><Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem class={styles.multiLabel} label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '索赔单号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        <Input placeholder={formatMessage({
                                            id: 'newPanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={data.code} disabled />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.operation.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateBrandId}
                                        required>
                                        {this.props.id ? `(${data.brandCode})${data.brandName}` : <div onClick={this.onClickStopPropagation}><WrappedSelect
                                            name="brandId"
                                            options={this.props.initEnum.brands}
                                            value={data.brandId}
                                            onChange={this.onChangeBrand} /></div>}
                                    </FormItem>
                                </Col>
                                {this.props.id && <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.operation.vin',
                                            defaultMessage: 'VIN'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateBrandId}
                                        required>
                                        {data.vin}
                                    </FormItem>
                                </Col>}
                            </Row>
                            {!this.props.id && <Row>
                                <Col>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.vin',
                                            defaultMessage: 'VIN'
                                        })}
                                        {...{
                                            colon: true,
                                            labelCol: {
                                                xxl: {span: 3},
                                                xl: {span: 5},
                                                md: {span: 5}
                                            },
                                            wrapperCol: {
                                                xxl: {span: 13},
                                                xl: {span: 19},
                                                md: {span: 19}
                                            }
                                        }}
                                        validateStatus={validateVehicle}
                                        required>
                                        {<div onClick={this.onClickStopPropagation}><SearchSelect
                                            showCopyButton={true}
                                            value={vehicleInfo}
                                            placeholder={this.props.intl.formatMessage({
                                                id: 'newPanel.form.vin.placeholder',
                                                defaultMessage: '请输入VIN进行查询'
                                            })}
                                            onSelect={this.onSelectVehicle}
                                            onSearch={this.onSearchVehicle}
                                            keyIndex="id"
                                            labelMap={this.vehicleLabelMap}
                                            onClickSearchBtn={this.onClickVehicle} /></div>
                                        }
                                        {this.props.id && data.vin}
                                    </FormItem>
                                </Col>
                            </Row>}
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.operation.repairType',
                                            defaultMessage: '索赔类型'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateRepairType}
                                        required>
                                        {
                                            <div onClick={this.onClickStopPropagation}><WrappedSelect
                                                disabled={!data.vehicleStatus}
                                                name="repairType"
                                                value={data.repairType}
                                                options={data.vehicleStatus === vehicleStatus.实销完成 ? repairTypeSaleList : repairTypeUnSaleList}
                                                onChange={this.onChangeRepairType} /></div>
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem class={styles.multiLabel} label={formatMessage({
                                        id: 'newPanel.operation.repairCode',
                                        defaultMessage: '维修单号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateRepairCode}
                                    required>
                                        <div onClick={this.onClickStopPropagation}><TextInput
                                            name="repairCode"
                                            value={data.repairCode}
                                            onBlur={this.onChange} /></div>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem class={styles.multiLabel} label={formatMessage({
                                        id: 'newPanel.operation.claimApplyCode',
                                        defaultMessage: '索赔预申请单号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateClaimApplyId}
                                    required={data.isOtherArea}>
                                        {this.props.id ? data.claimApplyCode : <div onClick={this.onClickStopPropagation}><SearchInput
                                            disabled={true}
                                            value={data.claimApplyCode}
                                            id={data.claimApplyId}
                                            onClickSearchBtn={this.onClickClaimApply} /></div>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.repairDate',
                                            defaultMessage: '维修日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateRepairDate}
                                        required>
                                        <div onClick={this.onClickStopPropagation}><WrappedDatePicker
                                            name="repairDate"
                                            disabledDate={this.disabledDate}
                                            value={data.repairDate}
                                            onChange={this.onChangeRepairDate}/></div>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.salesDealerCode',
                                        defaultMessage: '经销商'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.subDealerCode && this.state.validate ? 'error' : null}
                                    required>
                                        <div onClick={this.onClickStopPropagation}><DealerSelectPanel
                                            value={dealerInfo}
                                            getDealerSimple={subDealersQuickly}
                                            getDealers={subDealersQuery}
                                            onSelect={this.onSelectDealer} /></div>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.mileage',
                                        defaultMessage: '行驶里程'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.mileage && this.state.validate ? 'error' : null}
                                    required>
                                        <div onClick={this.onClickStopPropagation}><LocalizeInputNumber
                                            name="mileage"
                                            value={data.mileage}
                                            max={1000000000}
                                            min={0}
                                            onBlur={this.onChange} /></div>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.saleDate',
                                        defaultMessage: '实销日期'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.saleDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.shipDate',
                                        defaultMessage: '发车日期'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.shipDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.productionDate',
                                        defaultMessage: '生产日期'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.productionDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form></Col></Row>}>
                            <Form>
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.isOtherArea',
                                                defaultMessage: '是否跨区域索赔'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <Checkbox
                                                checked={data.isOtherArea}
                                                name="isOtherArea"
                                                value={data.isOtherArea}
                                                onChange={this.onIsOtherAreaCheck}>
                                            </Checkbox>
                                        </FormItem>
                                    </Col>
                                    {
                                        !data.claimApplyId && <Col {...FORM_OPTIONS.col}>
                                            <FormItem class={styles.multiLabel} label={formatMessage({
                                                id: 'newPanel.operation.subClaimCode',
                                                defaultMessage: '经销商申请单号'
                                            })} {...FORM_OPTIONS.item}>
                                                {
                                                    // eslint-disable-next-line no-nested-ternary
                                                    this.props.id ? data.subClaimCode : (this.props.isInput ? <SearchInput
                                                        disabled={Boolean(data.claimApplyId)}
                                                        value={data.subClaimCode}
                                                        id={data.subClaimId}
                                                        onClickSearchBtn={this.onClickSubClaim} /> : <TextInput
                                                        name="subClaimCode"
                                                        value={data.subClaimCode}
                                                        onBlur={this.onChange} />)
                                                }
                                            </FormItem>
                                        </Col>}
                                    {data.subClaimId && <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.claimApplyCreateTime',
                                                defaultMessage: '预申请日期'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            {formatDateTime(data.claimApplyCreateTime, DATE_FORMAT)}
                                        </FormItem>
                                    </Col>}
                                    {
                                        data.repairType === repairTypeSale.备件索赔 &&
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem
                                                label={this.props.intl.formatMessage({
                                                    id: 'newPanel.form.partPurchasedDate',
                                                    defaultMessage: '自费购件时间'
                                                })}
                                                {...FORM_OPTIONS.item}
                                                validateStatus={validatePartPurchasedDate}
                                                required>
                                                <WrappedDatePicker
                                                    name="partPurchasedDate"
                                                    value={data.partPurchasedDate}
                                                    onChange={this.onChange}/>
                                            </FormItem>
                                        </Col>
                                    }
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.createName',
                                                defaultMessage: '索赔人'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            {this.props.id ? data.creatorName : this.props.user}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.createTime',
                                                defaultMessage: '申请日期'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            {formatDateTime(dateTime, DATE_FORMAT)}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </Panel>
                        <Panel id="components-anchor-vehicleInfo" header={<Row>
                            <Col span={10}>{formatMessage({
                                id: 'newPanel.card.vehicleInfo',
                                defaultMessage: '车辆信息'
                            })}<Divider type="vertical" />{formatMessage({
                                id: 'newPanel.operation.productCategoryCode',
                                defaultMessage: '车型编号'
                            })}{': '}{data.productCategoryCode}</Col></Row>} key="2">
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.wholesaleDealerCode',
                                        defaultMessage: '总代'
                                    })} {...FORM_OPTIONS.item}>
                                        {this.props.enterprise ? `(${this.props.enterprise.code})${this.props.enterprise.name}` : ''}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {this.props.enterprise ? this.props.enterprise.country : ''}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.engineCode',
                                        defaultMessage: '发动机号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.engineCode && this.state.validate ? 'error' : null}
                                    required>
                                        <TextInput
                                            name="engineCode"
                                            value={data.engineCode}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.transmissionSn',
                                        defaultMessage: '变速箱号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.transmissionSn && this.state.validate ? 'error' : null}
                                    required>
                                        <TextInput
                                            name="transmissionSn"
                                            value={data.transmissionSn}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.productCategoryName',
                                        defaultMessage: '车型名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.productCategoryName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.annoucementNumber',
                                        defaultMessage: '公告号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.annoucementNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.customerSoldType',
                                        defaultMessage: '客户性质'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(customerType, data.customerSoldType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.isKD',
                                        defaultMessage: 'CBU/KD索赔'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.isKD === true && formatMessage({
                                            id: 'newPanel.operation.kd',
                                            defaultMessage: 'KD'
                                        })}
                                        {data.isKD === false && formatMessage({
                                            id: 'newPanel.operation.cbu',
                                            defaultMessage: 'CBU'
                                        })}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.customerName',
                                        defaultMessage: '用户姓名'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.customerName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.cellPhoneNumber',
                                        defaultMessage: '用户电话'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.cellPhoneNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.companyName',
                                        defaultMessage: '用户公司'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.companyName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.address',
                                        defaultMessage: '用户地址'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.address}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.email',
                                        defaultMessage: '用户Email'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.email}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Panel>
                    </Collapse>
                    <Collapse defaultActiveKey={['1', '2', '3', '4', '5', '6']}>
                        <Panel id="components-anchor-material" header={formatMessage({
                            id: 'newPanel.operation.claimMaterialDetails',
                            defaultMessage: '材料清单'
                        })}
                        extra={<Button
                            size="small"
                            onClick={this.onClickAddBtn}>
                            {formatMessage({
                                id: 'newPanel.operation.newDetail',
                                defaultMessage: '新增材料'
                            })}
                        </Button>} key="1">
                            <Row className={styles.materialSupplier}>
                                <Form className="form-standard">
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={<span>{formatMessage({
                                                id: 'newPanel.form.supplierId',
                                                defaultMessage: '供应商'
                                            })}
                                            <a style={{
                                                marginLeft: '8px'
                                            }}
                                            title={formatMessage({
                                                id: 'newPanel.form.supplierId',
                                                defaultMessage: '供应商'
                                            })}
                                            onClick={this.onClickSupplierBtn}>
                                                {this.state.isSupplier ? <Icon type="redo" /> : <Icon type="edit" />}
                                            </a></span>}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={!data.supplierCode && this.state.validate ? 'error' : null}
                                            required>
                                            {supplierComp}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.operation.faultType',
                                                defaultMessage: '故障类型'
                                            })}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={validateFaultType}
                                            required>
                                            <div onClick={this.onClickStopPropagation}><WrappedSelect
                                                name="faultType"
                                                value={data.faultType}
                                                options={faultTypeList}
                                                onChange={this.onChange} /></div>
                                        </FormItem>
                                    </Col>
                                </Form>
                            </Row>
                            <Row>
                                <MaterialTablePanel
                                    key={data.brandId}
                                    brandId={data.brandId}
                                    onSelectParts={this.onSelectParts}
                                    onDeletePart={this.onDeletePart}
                                    onDeleteAllParts={this.onDeleteAllParts}
                                    onPartQuantityChange={this.onPartQuantityChange}
                                    onCausedCheck={this.onCausedCheck}
                                    productCategoryCode={data.productCategoryCode}
                                    repairDate={data.repairDate}
                                    isMoneyVisible={this.props.isMoneyVisible}
                                    data={claimMaterialDetails}/>
                            </Row>
                            <Row>
                                <Col>
                                    {this.props.id ? (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.faultItem',
                                                defaultMessage: '故障代码'
                                            })}
                                            {...FORM_ROW_OPTIONS.item}>
                                            <span className="value-font">{data.faultItemName}</span>
                                        </FormItem>
                                    ) : (
                                        <FormItem
                                            label={<span>
                                                {formatMessage({
                                                    id: 'newPanel.form.faultItem',
                                                    defaultMessage:
                                                                '故障代码'
                                                })}
                                                <a style={{
                                                    marginLeft: '8px'
                                                }}
                                                title={formatMessage({
                                                    id: 'newPanel.form.faultItemReturn',
                                                    defaultMessage: '返回'
                                                })}
                                                onClick={this.onClickFaultItemBtn}>
                                                    {data.faultItemCnName === '其他' && <Icon type="undo" />}
                                                </a>
                                            </span>}
                                            {...FORM_ROW_OPTIONS.item}
                                            validateStatus={validateFaultItem}
                                            required>
                                            {data.faultItemCnName === '其他' && this.state.isFaultItem === false
                                                ? <div onClick={this.onClickStopPropagation}><TextInput
                                                    name="faultItemName"
                                                    value={data.faultItemName}
                                                    onBlur={this.onChange} /></div> : <div onClick={this.onClickStopPropagation}>
                                                    <FaultItemSelectPanel
                                                        value={faultItemInfo}
                                                        onSelect={this.onSelectFaultItem} />
                                                </div>}
                                        </FormItem>
                                    )}
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    {this.props.id ? (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.faultMode',
                                                defaultMessage: '故障原因'
                                            })}
                                            {...FORM_ROW_OPTIONS.item}>
                                            <span className="value-font">({data.faultModeCode}) {data.faultModeName}</span>
                                        </FormItem>
                                    ) : (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'newPanel.form.faultMode',
                                                defaultMessage: '故障原因'
                                            })}
                                            {...FORM_ROW_OPTIONS.item}
                                            validateStatus={validateFaultMode}
                                            required>
                                            {data.faultModeName === 'Other' ? <div onClick={this.onClickStopPropagation}><TextInput
                                                name="faultModeName"
                                                value={data.faultModeName}
                                                onBlur={this.onChange} /></div> : <div onClick={this.onClickStopPropagation}><SearchSelect
                                                value={faultModeInfo}
                                                placeholder={this.props.intl.formatMessage({
                                                    id: 'newPanel.form.faultMode.placeholder',
                                                    defaultMessage: '请输入故障原因名称或编号进行查询'
                                                })}
                                                onSelect={this.onSelectFaultMode}
                                                onSearch={this.onSearchFaultMode}
                                                keyIndex="id"
                                                labelMap={this.labelMap}
                                                onClickSearchBtn={this.onClickFaultMode} /></div>
                                            }
                                        </FormItem>
                                    )}
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.faultDescription',
                                        defaultMessage: '详细故障描述'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            className={styles.textInputClore}
                                            type="textarea"
                                            name="faultDescription"
                                            value={data.faultDescription}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Panel>
                        <Panel header={formatMessage({
                            id: 'newPanel.operation.claimAth',
                            defaultMessage: '附件清单'
                        })} key="2">
                            {
                                data.repairType === repairType.备件索赔 ? claimAthTypeList.map(item => (
                                    <ClaimAthPanel
                                        key={item.value}
                                        type={item.value}
                                        onRemovePhoto={this.onRemovePhoto}
                                        onRemoveFile={this.onRemoveFile}
                                        claimAthDetails={this.state.claimAthDetails}
                                        onChangeUploadPhoto={this.onChangeUploadPhoto}
                                        onChangeUploadFile={this.onChangeUploadFile}/>
                                )) : tuClaimAthTypeList.map(item => (
                                    <ClaimAthPanel
                                        key={item.value}
                                        type={item.value}
                                        onRemovePhoto={this.onRemovePhoto}
                                        onRemoveFile={this.onRemoveFile}
                                        claimAthDetails={this.state.claimAthDetails}
                                        onChangeUploadPhoto={this.onChangeUploadPhoto}
                                        onChangeUploadFile={this.onChangeUploadFile}/>
                                ))
                            }
                        </Panel>
                        <Panel header={formatMessage({
                            id: 'newPanel.operation.claimWorkItemDetails',
                            defaultMessage: '项目清单'
                        })}
                        extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickAddWorkItem}>
                                {formatMessage({
                                    id: 'newPanel.operation.newWorkItem',
                                    defaultMessage: '新增项目'
                                })}
                            </Button>
                        </div>} key="3">
                            <WorkItemTablePanel
                                key={data.id}
                                isMoneyVisible={this.props.isMoneyVisible}
                                onDeleteWorkItem={this.onDeleteWorkItem}
                                onDeleteAllWorkItem={this.onDeleteAllWorkItem}
                                onWorkItemLaborHourChange={this.onWorkItemLaborHourChange}
                                data={claimWorkItemDetails}/>
                        </Panel>
                        <Panel header={formatMessage({
                            id: 'newPanel.operation.isAccessory',
                            defaultMessage: '辅料清单'
                        })}
                        extra={<div>
                            <Button
                                size="small"
                                name="accessory"
                                onClick={this.onClickAddAccessoryBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.newAccessory',
                                    defaultMessage: '新增辅料'
                                })}
                            </Button>
                        </div>} key="4">
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="usedPartId"
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </Panel>
                        {
                            !data.isOtherArea && <Panel id="components-anchor-claimHistory" header={formatMessage({
                                id: 'newPanel.operation.claimHistory',
                                defaultMessage: '历史索赔信息'
                            })} key="5">
                                <ClaimHistoryPanel data={claimHistories} />
                            </Panel>
                        }
                        {data.id && <Panel header={formatMessage({
                            id: 'newPanel.operation.claimApprovedHis',
                            defaultMessage: '历史审核信息'
                        })} key="6">
                            <Table
                                className="white-space-nowrap"
                                columns={columResults}
                                rowKey="id"
                                pagination={false}
                                dataSource={claimApprovedHis}
                                {...TABLE} />
                        </Panel>}
                    </Collapse>
                    {!this.props.isMoneyVisible && <Card title={formatMessage({
                        id: 'newPanel.card.feeInfo',
                        defaultMessage: '索赔费用'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'newPanel.form.laborFee',
                                        defaultMessage: '工时费'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    {formatAmount(laborFee)}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'newPanel.form.materialFee',
                                        defaultMessage: '材料费'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    {formatAmount(materialFee)}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'newPanel.form.assistantFee',
                                        defaultMessage: '辅料费'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    {formatAmount(assistantFee)}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'newPanel.form.mgmtFee',
                                        defaultMessage: '管理费'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    {formatAmount(mgmtFee)}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'newPanel.form.totalFee',
                                        defaultMessage: '费用合计'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    {formatAmount(totalFee)}
                                </FormItem>
                            </Col>
                        </Row>
                    </Card>}
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                        <Button
                            type="primary"
                            onClick={this.onSubmitAndPreserve}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSubmitAndPreserve',
                                defaultMessage: '保存并提交'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showPartMultiSelectPanel &&
                        <PartMultiSelectPanel
                            currentSelectRowkeys={claimMaterialDetails}
                            brandId={data.brandId}
                            selectKey={data.id}
                            isMoneyVisible={this.props.isMoneyVisible}
                            productCategoryCode={data.productCategoryCode ? data.productCategoryCode : 'ProductCategoryCode'}
                            repairDate={data.repairDate}
                            onCancel={this.onClosePartMultiSelectPanel}
                            onSelect={this.onSelectPart} />
                    }
                    {
                        this.state.showClaimApply &&
                        <ClaimApplySelectPanel
                            selectLoading={loading}
                            vehicleSoldId={data.vehicleSoldId}
                            repairType={data.repairType}
                            selectKey={data.claimApplyId}
                            onCancel={this.onCloseClaimApply}
                            onSelect={this.onSelectClaimApply} />
                    }
                    {
                        this.state.showSubClaim &&
                        <SubClaimSelectPanel
                            vehicleSoldId={data.vehicleSoldId}
                            repairType={data.repairType}
                            subDealerId={data.salesDealerId}
                            selectKey={data.subClaimId}
                            onCancel={this.onCloseSubClaim}
                            onSelect={this.onSelectSubClaim} />
                    }
                    {
                        this.state.showFaultMode &&
                        <FaultModeSelectPanel
                            selectKey={data.faultModeId}
                            onCancel={this.onCloseFaultMode}
                            onSelect={this.onSelectFaultMode} />
                    }
                    {
                        this.state.showDutyUnit &&
                        <DutyUnitSelectPanel
                            type={dutyUnitType.索赔供应商}
                            isApprevor={false}
                            brandId={this.state.data.brandId}
                            selectKey={data.supplierId}
                            onCancel={this.onCloseDutyUnit}
                            onSelect={this.onSelectDutyUnit} />
                    }
                    {
                        this.state.showVehicle &&
                        <VehicleSoldSelectPanel
                            isOtherArea={data.isOtherArea}
                            selectKey={data.vehicleSoldId}
                            onCancel={this.onCloseVehicle}
                            onSelect={this.onSelectVehicle} />
                    }
                    {
                        this.state.showWorkItem &&
                        <WorkItemSelectPanel
                            currentSelectRowkeys={claimWorkItemDetails}
                            brandId={data.brandId}
                            productCategoryCode={data.productCategoryCode ? data.productCategoryCode : 'ProductCategoryCode'}
                            selectKey={data.workItemId}
                            onCancel={this.onCloseWorkItem}
                            onSelect={this.onSelectWorkItem} />
                    }
                    {
                        this.state.showPartAssistPanel &&
                        <PartAssistPanel
                            currentSelectRowkeys={details}
                            brandId={data.brandId}
                            selectKey={data.id}
                            partIds={partIds}
                            repairDate={data.repairDate}
                            productCategoryCode={data.productCategoryCode ? data.productCategoryCode : 'ProductCategoryCode'}
                            onCancel={this.onClosePartAssistPanel}
                            onSelect={this.onSelectPartAccessory} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    isInput: PropTypes.bool,
    user: PropTypes.string
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onSubmit
} from '../actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id,
            currency: item.currency
        })) : [];
        return {
            brands
        };
    }
);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getEnterprise = selectorFactory(['page', 'domainData', 'initData', 'enterprise']);
const mapStateToProps = (state, props) => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    isInput: state.getIn((['page', 'domainData', 'initData', 'isInput'])),
    user: state.getIn((['page', 'domainData', 'initData', 'user'])),
    isMoneyVisible: state.getIn((['page', 'domainData', 'initData', 'isMoneyVisible'])),
    initEnum: getinitEnumData(state),
    permissions: getPermissions(state),
    enterprise: getEnterprise(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, isSubmit) =>
        dispatch(onSubmit(data, details, claimWorkItemDetails, claimMaterialDetails, claimAthDetails, isSubmit)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
